<template>
  <!-- 新增直接调拨单 -->
  <div class="proOrderDetails" @click.stop="aotuTab=false">
    <div style="margin-bottom: 10px">
      <el-button size="mini" type="primary" @click="save">{{ $t('btn.save') }}</el-button>
    </div>
    <el-tabs v-model="activeName">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form ref="purchaseRef" :model="production" label-width="100px" size="mini">
          <el-form-item :label="$t('market.billType')">
            <el-select v-model="production.fbillType" filterable @change="saleHeadel">
              <el-option v-for="item in mostatusData" :key="item.fid" :label="item.fname" :value="item.fid" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.billNo')">
            <el-input v-model="production.fbillNo" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.orderDate')">
            <el-date-picker
              v-model.trim="production.fdate"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <!--          <el-form-item label="调拨组织">-->
          <!--            <el-select v-model.trim="production.fallotorgid">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item :label="$t('market.stocker')">
            <el-autocomplete
              v-model.trim="production.fstocker"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch3"
              @focus="querySalesperson(3)"
              @select="marketData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="marketVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fuserName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.note')">
            <el-input v-model="production.fnote" />
          </el-form-item>
        </el-form>
        <div style="margin-top: 10px;">
          <el-button size="mini" style="margin-bottom: 5px;" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
          <el-button size="mini" style="margin-bottom: 5px;" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
          <el-button size="mini" @click.native="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
        </div>
        <jc-table
          :table-data="tableData"
          :table-header="tableHeard"
          :table-height="tableHeight"
          serial
          :get-summaries="getSummaries"
          show-summary
          @rowClick="rowClick"
          @cellClick="cellClick"
        >
          <!--  物料编码  -->
          <template v-slot:billSlot="col">
            <el-input
              v-model.trim="col.scope.row.fnumber"
              size="mini"
              @input="getAtuo(col.scope.$index, col.scope.row.fnumber)"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="handleGetMateriel(col.scope.row, col.scope.$index)"
              />
            </el-input>
            <div v-if="aotuTab && material === col.scope.$index" :class="material<7 ? 'tabPosit': 'tabPosit1'">
              <number-code :fnumber="fnumber" @material="materialData" />
            </div>
          </template>
          <!--  数量  -->
          <template v-slot:tagSlot="col">
            <el-input-number v-model="col.scope.row.fqty" size="mini" />
          </template>
          <!--物料价值-->
          <template v-slot:text5Slot="col">
            <el-input-number
              v-model="col.scope.row.fworth"
              :min="0"
              size="mini"
            />
          </template>
          <!-- 转入仓库 -->
          <template v-slot:orderSlot="col">
            <el-input
              v-model="col.scope.row.ftoName"
              size="mini"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="handleWarehouse(col.scope.$index, 2)"
              />
            </el-input>
          </template>
          <!-- 转出仓库-->
          <template v-slot:operaSlot="col">
            <el-input
              v-model="col.scope.row.ffromName"
              size="mini"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="handleWarehouse(col.scope.$index, 1)"
              />
            </el-input>
          </template>
          <!--  调出组织  -->
          <template v-slot:text1Slot="col">
            <el-select
              v-model="col.scope.row.foutstockorgid"
              @change="col.scope.row.foutownerid=col.scope.row.foutstockorgid"
            >
              <el-option
                v-for="option in teamList"
                :key="option.fid"
                :label="option.fname"
                :value="option.fid"
              />
            </el-select>
          </template>
          <!--  调出货主  -->
          <template v-slot:text2Slot="col">
            <el-select
              v-model.trim="col.scope.row.foutownerid"
              disabled
            >
              <el-option
                v-for="option in teamList"
                :key="option.fid"
                :label="option.fname"
                :value="option.fid"
              />
            </el-select>
          </template>
          <!--  调入组织  -->
          <template v-slot:text3Slot="col">
            <el-select
              v-model.trim="col.scope.row.fstockorgid"
              @change="col.scope.row.fownerid=col.scope.row.fstockorgid"
            >
              <el-option
                v-for="option in teamList"
                :key="option.fid"
                :label="option.fname"
                :value="option.fid"
              />
            </el-select>
          </template>
          <!--  调入货主  -->
          <template v-slot:text4Slot="col">
            <el-select v-model.trim="col.scope.row.fownerid" disabled>
              <el-option
                v-for="option in teamList"
                :key="option.fid"
                :label="option.fname"
                :value="option.fid"
              />
            </el-select>
          </template>
          <!--  备注  -->
          <template v-slot:btnSlot="col">
            <el-input v-model="col.scope.row.fremark" size="mini" />
          </template>
        </jc-table>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.fince')" name="two">
        <el-form :model="production" label-width="100px" size="mini">
          <el-form-item :label="$t('market.settleCurr')"> <!--结算币别-->
            <el-autocomplete
              v-model.trim="production.fsettleCurr"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch5"
              size="mini"
              @focus="queryTBdCurrency"
              @select="currencyData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="currencyVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.exchangeType')"><!--汇率类型-->
            <el-input v-model.trim="production.fexchangeType" placeholder="请输入汇率类型" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.localCurr')"><!--本位币-->
            <el-input v-model.trim="production.flocalCurr" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.exchangeRate')"><!--汇率-->
            <el-input v-model.trim="production.fexchangeRate" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.worthall')"><!--总价zhi-->
            <el-input v-model.trim="production.fworthall" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.worthalllc')"><!--总价值(本位币)-->
            <el-input v-model.trim="production.fworthalllc" disabled size="mini" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <!--    物料弹窗-->
    <material v-if="isMateria" :msg="material" @material="materialData" />
    <!--结算币别列表-->
    <currency v-if="currencyVisiblit" @currency="currencyData" />
    <!-- 仓库 -->
    <selectCK
      v-if="seleceVisiblit"
      :fmaterial-id="stockFnumber"
      :msg="msg"
      @client="selectCK"
    />
    <!--销售员列表-->
    <market v-if="marketVisiblit" :staff-type="3" @market="marketData" />
  </div>
</template>

<script>
import {
  createStkAllot
} from '@/api/repertory/allot'
import { queryFxxchange, queryRate, queryViewItem } from '@/api/marketManage/marketOrder'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import bility from '@/mixin/Operability'

export default {
  name: 'CreateAllot',
  components: {
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    material: () => import('@/views/market/marketManage/createMarkerOrder/components/material'),
    numberCode: () => import('@/components/NumberCode'),
    market: () => import('@/views/market/marketManage/createMarkerOrder/components/market'),
    selectCK: () => import('@/views/production/collect/components/seleceCK')
  },
  mixins: [autocomplete, bility],
  data() {
    return {
      stockFnumber: '',
      seleceVisiblit: false, // 仓库
      marketVisiblit: false, // 仓管
      currencyVisiblit: false, // 币别
      activeName: 'first',
      msg: 1,
      stateColor: '', // 状态颜色
      production: {
        fallotorgid: '',
        fstockerId: '',
        fbillNo: '',
        fstocker: '',
        fdate: new Date().toLocaleDateString().replaceAll('/', '-'),
        fbillType: 196
      },
      fnumber: '',
      isMateria: false,
      aotuTab: false,
      tableHeight: '72vh',
      mostatusData: [], // 单据类型
      Entrys: [],
      material: 0,
      tableData: [{
        fnumber: '',
        fmodel: '',
        fspecificaTion: '',
        fdescripTion: '',
        funitName: '',
        fqty: 0,
        fworth: 0,
        ftoName: '',
        ffromName: '',
        stockQty: '',
        fremark: '',
        fstockorgid: '',
        fownerid: '',
        foutstockorgid: '',
        foutownerid: ''
      }],
      tableHeard: [
        { label: this.$t('market.fmaterial'), type: 'bill', prop: 'fnumber', width: '150px' },
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '200px' },
        { label: this.$t('market.funit'), prop: 'funitName', width: '80' },
        { label: this.$t('market.fqty'), type: 'tag', prop: 'fqty', width: '80' },
        { label: this.$t('market.globalValue'), type: 'text5', prop: 'fworth', width: '90px' },
        { label: this.$t('market.fromStock'), type: 'operate', prop: 'ffromName' },
        { label: this.$t('market.fromStockQty'), prop: 'stockQty' },
        // { label: '调出组织', type: 'text1' },
        // { label: '调出货主', type: 'text2' },
        { label: this.$t('market.toStock'), type: 'order', prop: 'ftoName' },
        { label: this.$t('market.toStockQty'), prop: 'ftoQty' },
        // { label: '调入组织', type: 'text3' },
        // { label: '调入货主', type: 'text4' },
        { label: this.$t('market.note'), type: 'btn', prop: 'fremark' }
      ]
    }
  },
  created() {
    this.business()
    this.saleHeadel()
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 265px)' : '72vh'
  },
  methods: {
    // 监听单据
    saleHeadel() {
      const DATA = {
        fid: this.production.fbillType || 0,
        viewName: 'SX_ALLOTBILLTYPE'
      }
      queryFxxchange(DATA).then(res => {
        if (res.code === 0) {
          this.production = {
            ...this.production,
            ...res.data
          }
          // this.production.fallotorgid = Number(res.data.fsaleorgid)
          // this.tableData.map(item => {
          //   item.fstockorgid = this.production.fallotorgid
          //   item.fownerid = this.production.fallotorgid
          //   item.foutstockorgid = this.production.fallotorgid
          //   item.foutownerid = this.production.fallotorgid
          // })
        }
      })
    },
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.material = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber = fnumber
      }, 600)
    },
    // 保存
    save() {
      const DATA = {
        ...this.production,
        details: this.tableData
      }
      createStkAllot(DATA).then(res => {
        if (res.code === 0) {
          this.tableData = []
          this.production = {
            fstockerId: '',
            fstocker: '',
            fdate: new Date().toLocaleDateString().replaceAll('/', '-'),
            fbillType: 196
          }
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: `/allotDetail/${res.data.fid}` })
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 单据类型
    business() {
      queryViewItem({ viewName: 'SX_ALLOTBILLTYPE' }).then(res => {
        this.mostatusData = res.data.list
      })
    },
    // 打开物料弹窗
    handleGetMateriel(row, index) {
      this.isMateria = true
      this.material = index
    },
    // 物料数据
    materialData(item) {
      if (item.fmaterialId) {
        const items = this.tableData[this.material]
        items.fmaterialId = item.fmaterialId
        items.fnumber = item.fnumber
        items.fname = item.fname
        items.fdescripTion = item.fdescripTion
        items.fspecificaTion = item.fspecificaTion
        items.funitId = item.funitId
        items.funitName = item.funit
        items.fmodel = item.fmodel
      }
      this.isMateria = item.isMaterialDialog
    },
    // 打开仓库弹窗
    handleWarehouse(index, ev) {
      const item = this.tableData[index].fnumber
      if (!item) {
        this.$message.warning('请先选择物料编码！！！')
        return
      }
      this.msg = ev // 转入转出仓库
      this.indexSelf = index
      this.stockFnumber = item
      this.seleceVisiblit = true
    },
    // 获取仓库数据
    selectCK(ev) {
      if (ev.fstockId) {
        const item = this.tableData[this.indexSelf]
        if (this.msg === 1) { // 转出
          item.ffromId = ev.fstockId
          item.ffromName = ev.fname
          item.stockQty = ev.sumQty
        } else { // 转入
          item.ftoId = ev.fstockId
          item.ftoName = ev.fname
          item.ftoQty = ev.sumQty
        }
      }
      this.seleceVisiblit = false
    },
    // 获取仓管员数据(子传父)
    marketData(item) {
      if (item.fuserId) {
        this.production.fstocker = item.fuserName
        this.production.fstockerId = item.fuserId
      }
      this.marketVisiblit = false
    },
    // 获取结算币别数据(子传父)
    currencyData(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.production.fsettleCurr = item.fsettleCurrIdName || item.fname
        this.production.fsettleCurrId = item.fsettleCurrId || item.fcurrencyId
        this.production.flocalCurrId && this.querySalerRate()
      }
      this.currencyVisiblit = false
    },
    // 查询销售订单汇率
    async querySalerRate() {
      const DATA = {
        tocurrId: this.production.flocalCurrId, // 本位币
        fromcurrId: this.production.fsettleCurrId, // 结算币别
        queryDate: this.production.fdate
      }
      const { data: RES, code, message } = await queryRate(DATA)
      if (code === 0) {
        this.production.fexchangeRate = RES.exchangeRate
        this.production.fexchangeType = RES.exchangeTypeName
        this.production.fexchangeTypeId = RES.exchangeTypeId
      } else {
        this.production.fexchangeRate = ''
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增行
    newHang() {
      const DATA = {
        fnumber: '',
        fmodel: '',
        fspecificaTion: '',
        fdescripTion: '',
        funitName: '',
        fqty: 0,
        fworth: 0,
        ftoName: '',
        ffromName: '',
        stockQty: '',
        fstockorgid: this.production.fallotorgid,
        fownerid: this.production.fallotorgid,
        foutstockorgid: this.production.fallotorgid,
        foutownerid: this.production.fallotorgid,
        fremark: ''
      }
      this.tableData.push(DATA)
    },
    // 删除行
    delHang() {
      this.tableData.splice(this.indexSelf, 1)
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.tableData[this.subscript][this.property]
      const ite = this.tableData[this.subscript]
      this.tableData.map((res, index) => {
        if (index >= this.subscript) {
          if (this.property === 'ffromName') {
            res.ffromId = ite.ffromId
            res.stockQty = ite.stockQty
          } else if (this.property === 'ftoName') {
            res.ftoId = ite.ftoId
            res.ftoQty = ite.ftoQty
          }
          res[this.property] = item
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.proOrderDetails {
  @include listBom;
  .el-tabs {
    &::v-deep .el-tabs__content {
      min-height: 80vh;
    }
    .tabPosit {
      padding: 5px;
      box-shadow: 0 0 2px #aaa;
      position: absolute;
      top: 3.5vh;
      left: 0;
      background-color: rgba(255, 255, 255, 1);
      z-index: 99999!important;
    }
    .tabPosit1 {
      padding: 5px;
      box-shadow: 0 0 2px #aaa;
      position: absolute;
      top: -25.69vh;
      left: 0;
      background-color: rgba(255, 255, 255, 1);
      z-index: 9999;
    }
    .el-input::v-deep .el-input__inner {
      height: 30px;
      line-height: 30px;
    }
    .el-form {
      display: flex;
      flex-wrap: wrap;

      .el-form-item {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 35px;
        width: 275px;
        margin-bottom: 5px;

        .btnType {
          margin-right: 5px;
        }

        .el-date-editor.el-input {
          width: 100% !important;
        }

        .el-select {
          width: 100%;
        }
      }
    }
  }
}
</style>
